<template>
  <base-breadcrumb class="allPlan">
    <searchData :search-data="searchArr" @search="search" />
    <a-card :bordered="false">
      <!-- <div class="table-operator">
        <div class="pub-table-action-btn">
          <a-button
            v-btnPermission="'mm_001_add_01'"
            type="primary"
            icon="plus"
            @click="handleEdit(null,1)"
          >
            新增
          </a-button>

          <excel
            ref="exportSelect"
            file-name="物资需求总计划列表"
            is-click-generate="false"
          >
            <a-button
              slot="excelBtn"
              @click="exportSelect"
            >
              导出选中
            </a-button>
          </excel>
          <excel
            ref="exportAll"
            file-name="物资需求总计划列表"
            is-click-generate="false"
          >
            <a-button
              slot="excelBtn"
              @click="exportAll"
            >
              导出全部
            </a-button>
          </excel>
        </div>
        <div class="pub-table-select-count">
          <a-icon
            type="info-circle"
            theme="twoTone"
          />
          已选择{{ selectedRowKeys.length }}项

          <span>
            总计：{{ totalSize }}，
            待提交审核：{{ statistics.draft }}，
            审核中：{{ statistics.submitted }}，
            审核通过：{{ statistics.past }}，
            审核不通过：{{ statistics.rejected }}，
            已作废：{{ statistics.delete }}，
            已变更：{{ statistics.change }}
          </span>
        </div>
      </div> -->
      <!-- <a-table
        ref="table"
        :scroll="{x:2000}"
        :loading="loading"
        :columns="columns"
        :data-source="tableData"
        :pagination="false"
        row-key="id"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @expand="getChildList"
      > -->
      <list-table
        ref="table"
        :pageKeys="['pageNum', 'pageSize', 'totalSize']"
        :columns="columns"
        :startIndex="0"
        :request="loadData"
        :exportPermission="{ select: '', all: '' }"
        :exportConfig="{ use: true, select: $route.meta.title, all: $route.meta.title }"
        :statistics-config="{ use: true, statistics, temp }"
        @expand="getChildList"
      >
        <template slot="prefix">
            <a-button
            v-btnPermission="'mm_001_add_01'"
            type="primary"
            icon="plus"
            @click="handleEdit(null,1)"
          >
            新增
          </a-button>
        </template>
        <div slot="expandedRowRender">
          <p class="total-plan-list-title">钢筋需用总计划</p>
          <a-table :columns="childColumns" :data-source="rebarTable" :pagination="false" :loading="childrenLoading" />
          <p class="total-plan-list-title concrete-title">混凝土需用总计划</p>
          <a-table :columns="concreteColumns" :data-source="concreteTable" :pagination="false" :loading="childrenLoading" />
        </div>
        <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
        <template slot="auditStatusStr" slot-scope="text, record">
          <list-status :status="record.auditStatus" :text="text" />
        </template>
        <template slot="operation" slot-scope="text, record">
          <MoreButton>
              <a @click="handleEdit(record, 3)">查看</a>
              <a v-if="editStatus(record)&&hideBuquBtn()" @click="handleEdit(record, 2)">编辑</a>
              <template v-if="record.auditStatus === 'DRAFT'&&hideBuquBtn()">
                <a @click="handleDel(record.id)">删除</a>
              </template>
              <a
                v-if="record.auditStatus === 'PAST' || record.auditStatus === 'SUBMITTED' || record.auditStatus === 'REJECTED'"
                @click="
                  chooseId = record.id
                  $refs.approval.open()
                "
                >审批历史</a
              >
          </MoreButton>
        </template>
      </list-table>
      <!-- <pagination
        v-model="pageNo"
        :total="totalSize"
        :page-size.sync="pageSize"
        @change="handlePageChange"
        @showSizeChange="showSizeChange"
      /> -->
    </a-card>
    <!--        <history ref="history" title="审批历史" :btn-cb="openApprovalDetail"></history>-->
    <approval :id="chooseId" ref="approval" title="审批" tableTime="changeTime"/>
  </base-breadcrumb>
</template>

<script>
import { totalPlanList, totalPlanListDel, totalPlanListChild, findListCount } from '@/api/material/materialMasterPlan/materialPlan'
import approval from './components/approval'
import SelectSubCompany from '@/components/Select/SelectSubCompany'
import SelectProject from '@/components/Select/SelectProject'
import OrgTreeSelect from '@/components/OrgTreeSelect'
import MoreButton from '@/components/MoreButton'

export default {
  name: 'a' + Date.now(),
  components: { approval, MoreButton },
  data() {
    return {
      loading: false,
      childrenLoading: false,
      chooseId: '',
      visible: false,
      pageNo: 1,
      pageSize: 10,
      totalSize: 0,
      selectedRowKeys: [],
      selectId: [],
      selectedRows: [],
      chooseData: 0,
      tableData: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          scopedSlots: { customRender: 'index' },
          width: 70
        },
        {
          title: '所属分公司',
          dataIndex: 'branchCompany',
          width: 120
        },
        { title: '物资需求总计划编码', dataIndex: 'masterPlanCode', width: 160 },
        { title: '项目名称', dataIndex: 'projectName', width: 400 },
        { title: '编号', dataIndex: 'code', width: 240 },
        { title: '钢筋总量/t', dataIndex: 'bars', width: 100 },
        { title: '混凝土总量/m³', dataIndex: 'concrete', width: 140 },
        { title: '创建人', dataIndex: 'creatorName', width: 200 },
        { title: '创建时间', dataIndex: 'createTime', width: 160 },
        {
          title: '状态',
          dataIndex: 'auditStatusStr',
          width: this.STATUS_WIDTH,
          scopedSlots: { customRender: 'auditStatusStr' }
        },
        {
          title: '操作',
          key: 'operation',
          scopedSlots: { customRender: 'operation' },
          width: 210,
          fixed: 'right'
        }
      ],
      searchArr: [
        // 搜索框
        {
          name: '所属单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect,
        },
        // {
        //   name: '所属分公司',
        //   valueKey: 'branchCompanyId',
        //   type: SelectSubCompany
        // },
        // {
        //   name: '项目名称',
        //   type: SelectProject,
        //   valueKey: 'projectId'
        // },
        {
          name: '需求总计划编码',
          value: 'planCode',
          type: 'input'
        },
        {
          name: '编号',
          value: 'code',
          type: 'input'
        },
        {
          name: '创建人',
          value: 'creatorName',
          type: 'input'
        },
        {
          name: '创建时间',
          value: 'create',
          type: 'timeRangeFormat'
        },
        {
          name: '状态',
          type: 'select',
          value: 'auditStatus',
          data: [
            { label: '待提交审核', value: 'DRAFT', enabled: true },
            { label: '审核中', value: 'SUBMITTED', enabled: true },
            { label: '审核通过', value: 'PAST', enabled: true },
            { label: '审核不通过', value: 'REJECTED', enabled: true },
            { label: '已变更', value: 'CHANGE', enabled: true }
          ]
        }
      ],
      childColumns: [
        { title: '钢筋级别', dataIndex: 'name' },
        { title: '桩基', dataIndex: 'pileFoundation' },
        { title: '地下室', dataIndex: 'basement' },
        { title: '主体', dataIndex: 'subject' },
        { title: '二次结构', dataIndex: 'secondaryStructure' },
        { title: '合计', dataIndex: 'total' }
      ],
      concreteColumns: [
        { title: '混凝土标号', dataIndex: 'name' },
        { title: '桩基', dataIndex: 'pileFoundation' },
        { title: '地下室', dataIndex: 'basement' },
        { title: '主体', dataIndex: 'subject' },
        { title: '二次结构', dataIndex: 'secondaryStructure' },
        { title: '合计', dataIndex: 'total' }
      ],
      rebarTable: [],
      concreteTable: [],
      queryParam: {},
      statistics: {},
      pathName: this.$route.path,
      loadData: (params) => {
        let searchData = Object.assign(
          {
            pageSize: this.pageSize || this.totalSize,
            pageNo: this.pageNo
          },
          params,
          this.queryParam
        )
         findListCount(searchData).then((res) => {
        if (res.code === this.SUCCESS_CODE) this.statistics = res.data
      })
        return totalPlanList(searchData).then((res) => {
          return res
        })
      },
      temp: () => {
        return (
          <span>
            总计：{this.totalSize || 0}，
            待提交审核：{this.statistics.draft || 0}，
            审核中： {this.statistics.submitted || 0}，
            审核通过：{this.statistics.past || 0}，
            审核不通过： {this.statistics.rejected || 0},
            已作废： {this.statistics.delete || 0},
            已变更： {this.statistics.change || 0},
          </span>
        )
      }
    }
  },

  mounted: async function () {
    this.$refs.table.refresh(true)
    // this.list()
    // this.$refs.exportSelect.tableToExcelFile(this.$refs.table)
    // this.$refs.exportAll.tableToExcelFile(this.$refs.table)
    // console.log('mounted-----------table的Path', this.pathName)
    // 监听详情页返回刷新列表
    //this.pathName取的值是this.$route.path
    this.$bus.$on('handleRefresh' + this.pathName, () => {
      // console.log('--------------------收到了，刷新刷新刷新----------------',this.pathName)
      // this.list()
      this.$refs.table.refresh(true)
    })
  },
  beforeDestroy() {
    console.log('beforeDestroy-------table的Path', this.pathName)
    this.$bus.$off('handleRefresh' + this.pathName)
  },
  methods: {
    editStatus(record) {
      if (record.auditStatus !== 'SUBMITTED') {
        return true
      }
      return record.auditStatus === 'CHANGE' && record.changeUserId === this.$userInfo().id
    },
    openApprovalDetail(row, state) {
      this.$bus.$emit('showApprovalDetailsDialog', row.id)
    },
    openApprovalHistory(id) {
      this.$refs.history.open(id)
    },
    test(v) {
      console.log(v.target.value)
    },
    // exportSelect: function() {
    //   if (this.selectedRowKeys.length > 0) {
    //     this.$refs.exportSelect.setDataAndGenerate(this.selectedRows)
    //   } else {
    //     this.$message.warning('请选择需要导出的数据')
    //   }
    // },
    // exportAll: function() {
    //   // 参数：查询条件、导出的回调
    //   if (this.totalSize) {
    //     this.pageNo = 1
    //     this.list(false, this.$refs.exportAll.setDataAndGenerate)
    //   } else {
    //     this.$message.warning('没有可导出的数据')
    //   }
    // },
    getOption: function () {
      let _this = this
      selectOption({
        type: 11
      }).then((res) => {
        if (res.code === 200) {
          for (let i = 0; i < res.data.length; i++) {
            _this.searchArr[1].data.push({ label: res.data[i].name, value: res.data[i].id })
          }
        }
      })
    },
    getChildList: function (expanded, record) {
      let _this = this
      if (expanded) {
        this.childrenLoading = true
        totalPlanListChild({
          id: record.id
        }).then((res) => {
          if (res.code === 200) {
            _this.rebarTable = res.data.barsTotals
            _this.concreteTable = res.data.concreteTotals
          }
          this.childrenLoading = false
        }).catch(() => {
          this.childrenLoading = false
        })
      }
    },
    list(params, callback) {
      this.loading = true
      let _this = this
      let searchData = Object.assign(
        {
          pageSize: callback ? _this.totalSize : _this.pageSize,
          pageNo: _this.pageNo
        },
        params,
        this.queryParam
      )
      // if (searchData.createTime) {
      //     searchData.createStartTime = _this.formatDate(searchData.createTime[0])
      //     searchData.createEndTime = _this.formatDate(searchData.createTime[1])
      // }

      findListCount(searchData).then((res) => {
        if (res.code === this.SUCCESS_CODE) this.statistics = res.data
      })

      totalPlanList(searchData).then((res) => {
        console.log(res)
        if (res.code === 200) {
          if (callback) {
            if (res.data.length) {
              callback(res.data)
            } else {
              this.$message.warning('没有可导出的数据')
            }
            this.loading = false
            return
          }
          _this.tableData = res.data
          _this.totalSize = res.totalSize
        }
        this.loading = false
      })
    },
    search(val) {
      this.pageNo = 1
      this.queryParam = val
      // this.list(val)
      this.$refs.table.refresh(true)
    },
    // handlePageChange(pageNo, pageSize) {
    //   this.pageNo = pageNo
    //   this.list()
    //   this.selectedRowKeys = []
    // },
    // showSizeChange(pageNo, pageSize) {
    //   this.pageNo = 1
    //   this.pageSize = pageSize
    //   this.list()
    // },
    // onSelectChange(selectedRowKeys, selectedRows) {
    //   let _this = this
    //   _this.selectId = []
    //   selectedRows.map(item => {
    //     // 选中id
    //     _this.selectId.push(item.id)
    //   })
    //   this.chooseData = selectedRowKeys.length
    //   _this.selectedRowKeys = selectedRowKeys
    //   _this.selectedRows = selectedRows
    // },
    handleDel(id) {
      let _this = this
      let params = id ? [id] : _this.selectId
      _this.delList(
        totalPlanListDel,
        () => {
          _this.search()
          this.selectedId = []
          this.selectedRowKeys = []
          this.selectedRows = []
          this.editingKey = ''
        },
        { ids: params }
      )
    },
    handleEdit(record = {}, state) {
      this.$router.push({
        path: '/material/materialMasterPlanAdd',
        query: {
          id: (record && record.id) || '',
          targetPage:'list',
          state: state
        }
      })
    }
  }
}
</script>
